// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.patent.service.impl;

import com.liuxinlong.common.AosException;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.FileBusinessTypeEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.dao.FileManageDao;
import com.liuxinlong.modules.dao.PatentProductClassDao;
import com.liuxinlong.modules.dao.PatentTrendsDao;
import com.liuxinlong.modules.dao.PatentTrendsExpandDao;
import com.liuxinlong.modules.entity.FileManage;
import com.liuxinlong.modules.entity.PatentProductClass;
import com.liuxinlong.modules.entity.PatentTrends;
import com.liuxinlong.modules.entity.PatentTrendsExpand;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.patent.service.PatentTrendsService;
import com.liuxinlong.modules.system.service.FileManageService;
import com.liuxinlong.utils.ExcelUtils;
import com.liuxinlong.utils.IPUtils;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 专利动态信息实现类
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2023-09-15
 */
@Service
@Slf4j
public class PatentTrendsServiceImpl implements PatentTrendsService {

    @Autowired
    private PatentTrendsDao patentTrendsDao;

    @Autowired
    private FileManageDao fileManageDao;

    @Autowired
    private PatentTrendsExpandDao patentTrendsExpandDao;

    @Autowired
    private FileManageService fileManageService;

    @Autowired
    private PatentProductClassDao patentProductClassDao;


    @Override
    public Map<String, Object> queryPatentTrendsInfo(Map<String, Object> queryParam) {
        PatentTrends patentTrends = patentTrendsDao.queryPatentTrends(queryParam);
        if (ObjectUtils.isEmpty(patentTrends)) {
            return new HashMap<>();
        }
        Map<String, Object> resultMap = ObjectUtils.object2Map(patentTrends);
//        FileManage pictureInfo = fileManageDao.selectById(patentTrends.getTrendsPicture());
        String currentIp = IPUtils.getCurrentIp();
//        resultMap.put("pictureUrl", pictureInfo.getFilePath().replace("upload", "http:\\\\" + currentIp + ":8090\\preview\\upload"));
        queryParam.put("trendsId", patentTrends.getId());
        List<PatentTrendsExpand> patentTrendsExpandList = patentTrendsExpandDao.pagePatentTrendsExpand(queryParam);
        List<Map<String, Object>> expandList = new ArrayList<>(patentTrendsExpandList.size());
        if (!ObjectUtils.isEmpty(patentTrendsExpandList)) {
            Set<String> pictureSet = patentTrendsExpandList.stream().map(PatentTrendsExpand::getPicture).collect(Collectors.toSet());
            Map<String, Map<String, Object>> pictureMap = fileManageDao.getFileMapByIds(pictureSet);
            for (PatentTrendsExpand expand : patentTrendsExpandList) {
                Map<String, Object> item = ObjectUtils.object2Map(expand);
                if (pictureMap.containsKey(expand.getPicture())) {
                    item.put("pictureUrl", String.valueOf(pictureMap.get(expand.getPicture().trim()).get("path")).replace("upload", "http:\\\\" + currentIp + ":8090\\preview\\upload"));
                }
                expandList.add(item);
            }
        }
        int expandNum = patentTrendsExpandDao.getPatentTrendsExpandCount(queryParam);
        List<Map<String, Object>> chartDataList = patentTrendsExpandDao.queryChartData(patentTrends.getId());
        resultMap.put("expandList", expandList);
        resultMap.put("totalNum", expandNum);
        resultMap.put("chartDataList", chartDataList);
        return resultMap;
    }

    @Override
    public void addPatentTrends(PatentTrends patentTrends) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String trendsMonth = patentTrends.getTrendsMonth();
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("trendsMonth", trendsMonth);
        queryParam.put("productClass", patentTrends.getProductClass());
        PatentTrends oldTrends = patentTrendsDao.queryPatentTrends(queryParam);
        if (!ObjectUtils.isEmpty(oldTrends)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "已存在专利动态，请进行更新操作！");
        }
        String id = SnowFlake.nextIdStr();
        patentTrends.setId(id);

        List<String> attachList = new ArrayList<>();
        if (StringUtils.isNotEmpty(patentTrends.getTrendsPicture())) {
            attachList.add(patentTrends.getTrendsPicture());
        }
        attachList.add(patentTrends.getTrendsAttach());
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        List<PatentTrendsExpand> expandList = analysisTrendsData(patentTrends.getTrendsAttach(), currentUser, currentTime, id);
        if (!ObjectUtils.isEmpty(expandList)) {
            patentTrendsExpandDao.insertBatch(expandList);
            List<String> fileIds = expandList.stream().map(PatentTrendsExpand::getPicture).collect(Collectors.toList());
            attachList.addAll(fileIds);
        }
        String attachIds = StringUtils.deleteWhitespace(StringUtils.strip(attachList.toString(), "[]").replaceAll(" +", ""));
        fileManageService.updateBusinessFile(attachIds, id);
        patentTrends.setCreateUser(currentUser.getId());
        patentTrends.setCreateTime(currentTime);
        patentTrendsDao.insert(patentTrends);
    }

    @Override
    public void updatePatentTrends(PatentTrends patentTrends) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String trendsMonth = patentTrends.getTrendsMonth();
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("trendsMonth", trendsMonth);
        queryParam.put("productClass", patentTrends.getProductClass());
        PatentTrends oldTrends = patentTrendsDao.queryPatentTrends(queryParam);
        String id = patentTrends.getId();
        if (!ObjectUtils.isEmpty(oldTrends) && !StringUtils.equals(id, oldTrends.getId())) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "当前月份已存在该产品品类专利动态！");
        }
        PatentTrends oldData = patentTrendsDao.selectById(id);
        List<String> attachList = new ArrayList<>();
        if (StringUtils.isNotEmpty(patentTrends.getTrendsPicture())) {
            attachList.add(patentTrends.getTrendsPicture());
        }
        attachList.add(patentTrends.getTrendsAttach());
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        if (!StringUtils.equals(patentTrends.getTrendsAttach(), oldData.getTrendsAttach())) {
            patentTrendsExpandDao.deleteExpandInfo(id);
            List<PatentTrendsExpand> expandList = analysisTrendsData(patentTrends.getTrendsAttach(), currentUser, currentTime, id);
            if (!ObjectUtils.isEmpty(expandList)) {
                patentTrendsExpandDao.insertBatch(expandList);
                List<String> fileIds = expandList.stream().map(PatentTrendsExpand::getPicture).collect(Collectors.toList());
                attachList.addAll(fileIds);
            }
        } else {
            Map<String, Object> param = new HashMap<>();
            param.put("trendsId", patentTrends.getId());
            param.put("startNum", 0);
            param.put("pageSize", 10000);
            List<PatentTrendsExpand> expandList = patentTrendsExpandDao.pagePatentTrendsExpand(param);
            List<String> fileIds = expandList.stream().map(PatentTrendsExpand::getPicture).collect(Collectors.toList());
            attachList.addAll(fileIds);
        }
        if (!StringUtils.equals(patentTrends.getTrendsPicture(), oldData.getTrendsPicture()) && !StringUtils.equals(patentTrends.getTrendsAttach(), oldData.getTrendsAttach())) {
            String attachIds = StringUtils.deleteWhitespace(StringUtils.strip(attachList.toString(), "[]").replaceAll(" +", ""));
            fileManageService.updateBusinessFile(attachIds, id);
        }
        patentTrends.setUpdateUser(currentUser.getId());
        patentTrends.setUpdateTime(currentTime);
        patentTrendsDao.updateById(patentTrends);
    }

    @Override
    public void deletePatentTrends(String id) {

    }

    @Override
    public void exportPatentTrends(String id, HttpServletResponse response) {
        PatentTrends patentTrends = patentTrendsDao.selectById(id);
        if (ObjectUtils.isEmpty(patentTrends)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "专利动态不存在，导出失败！");
        }
        fileManageService.downloadFile(patentTrends.getTrendsAttach(), response);
    }

    @Override
    public void updateRecommendStatus(String id) {
        PatentTrendsExpand expand = patentTrendsExpandDao.selectById(id);
        if (ObjectUtils.isEmpty(expand)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "专利信息不存在，修改失败！");
        }
        expand.setRecommend(expand.getRecommend() == 1 ? 0 : 1);
        patentTrendsExpandDao.updateById(expand);
    }

    @Override
    public void checkTrendsStatus() {
        String currentDate = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD);
        String monthFirstWednesday = TimeUtils.firstWednesday();
        if (TimeUtils.compareDate(currentDate,monthFirstWednesday,TimeFormatConstants.YYYY_MM_DD) < 0) {
            return;
        }
        Map<String,Map<String,String>> monthTrendsMap = patentTrendsDao.queryExistPatentTrends(currentDate.substring(0,7));
        List<PatentProductClass> productClassList = patentProductClassDao.getProductClassList();
        for (PatentProductClass productClass : productClassList) {
            if (monthTrendsMap.containsKey(productClass.getId())) {
                continue;
            }

        }
    }

    private List<PatentTrendsExpand> analysisTrendsData(String fileId, User currentUser, String currentTime, String trendsId) {
        FileManage fileInfo = fileManageDao.selectById(fileId);
        List<String[]> fileContent;
        String filePath = fileInfo.getFilePath();
        List<PatentTrendsExpand> stepOneList = new ArrayList<>();
        List<PatentTrendsExpand> stepTwoList = new ArrayList<>();
        List<PatentTrendsExpand> dataList = new ArrayList<>();
        List<FileManage> pictureList = new ArrayList<>();
        try {
            fileContent = ExcelUtils.importExcel(filePath, 1);
            for (int i = 0; i < fileContent.size(); i++) {
                log.info("第{}行数据解析中", i);
                String[] record = fileContent.get(i);
                System.out.println(record.toString());
                PatentTrendsExpand item = new PatentTrendsExpand();
                item.setId(SnowFlake.nextIdStr());
                item.setTrendsId(trendsId);
                item.setSortNum(Math.toIntExact(Math.round(Float.parseFloat(record[0]))));
                item.setPatentNo(record[1]);
                item.setPicture(record[2]);
                item.setTitle(record[3]);
                item.setApplyNo(record[4]);
                item.setRemark(record[5]);
                item.setApply(record[6]);
                item.setRecommend(StringUtils.equals(record[7], "是") ? 1 : 0);
                stepOneList.add(item);
            }
            InputStream inputStream = new FileInputStream(filePath);
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            //获取超链接集合
            List<Hyperlink> hyperLinks = (List<Hyperlink>) sheet.getHyperlinkList();
            //遍历所有超链接
            for (int i = 0; i < hyperLinks.size(); i++) {
                //获取包含超链接的单元格行、列坐标
                int row = hyperLinks.get(i).getFirstRow();
                int column = hyperLinks.get(i).getFirstColumn();

                //获取超链接文本、地址
                String text = hyperLinks.get(i).getLabel();
                String address = hyperLinks.get(i).getAddress();

                //输出超链接获取结果
                System.out.println(String.format("单元格[%d, %d] 显示文本：", row, column) + text + "\n" + " 链接地址：" + address);
                PatentTrendsExpand item = stepOneList.get(i);
                item.setJumpUrl(address);
                stepTwoList.add(i, item);
            }

            //获取超链接集合
            Map<String, XSSFPictureData> map = ExcelUtils.getPictures((XSSFSheet) sheet);
            for (String mapKey : map.keySet()) {
                String pictureId = SnowFlake.nextIdStr();
                int rowNum = Integer.parseInt(mapKey.split("-")[0]);
                PatentTrendsExpand item = stepTwoList.get(rowNum - 1);

                XSSFPictureData xssfPictureData = map.get(mapKey);
                byte[] data = xssfPictureData.getData();
                String picturePath = FileBusinessTypeEnum.PATENT_TRENDS_ATTACH_PICTURE.getFolder() + "/" + pictureId + ".png";
                FileOutputStream out = new FileOutputStream(picturePath);
                out.write(data);
                out.close();
                FileManage fileManage = new FileManage();
                fileManage.setId(pictureId);
                fileManage.setName(item.getTitle());
                fileManage.setBusinessType(FileBusinessTypeEnum.PATENT_TRENDS_ATTACH_PICTURE.getValue());
                fileManage.setFileType("png");
                fileManage.setFilePath(picturePath);
                fileManage.setOperateUser(currentUser.getId());
                fileManage.setOperateTime(currentTime);
                pictureList.add(fileManage);

                item.setPicture(pictureId);
                dataList.add(item);
            }
        } catch (Exception e) {
            e.printStackTrace();
//            System.out.println();
            throw new AosException(ReturnCodes.HTTP_IMPORT_FAIL_READ_FILE.getRetCode(), "读取文件失败，文件路径=" + filePath);
        }
        if (!ObjectUtils.isEmpty(pictureList)) {
            fileManageDao.insertBatch(pictureList);
        }
        return dataList;
    }
}
